//
//  BinningBracketVC.m
//  CJRailTransport
//
//  Created by Hank on 2017/12/28.
//  Copyright © 2017年 amplity. All rights reserved.
//

#import "BinningBracketVC.h"
#import "BinningBracketCell.h"
#import "BinningBracketModel.h"
#import "ScanVC.h"
#import "StyleDIY.h"
#import "MAAFConfig.h"
#import "RailTransportDao.h"

@interface BinningBracketVC ()
// 支架或托盘数据数组
@property (strong ,nonatomic)NSMutableArray *scanDataArray;
// GPS数据数组
@property (strong ,nonatomic)NSMutableArray *GPSDataArray;

@end

@implementation BinningBracketVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航栏
    [self setNavC];
    // 设置界面属性
    [self setViewAttribute];
    // 注册Cell
    [self registerCells];
    // 恢复数据
    [self recoveryData];
}

#pragma mark - 导航栏
- (void)setNavC
{
    self.title = @"装支架";
    // 设置导航栏颜色
    BasicNavigationController *nVC = (BasicNavigationController *)self.navigationController;
    nVC.themeColor = [UIColor whiteColor];
    nVC.tintColor = [UIColor darkGrayColor];
}

// 设置界面属性
- (void)setViewAttribute
{
    self.view.backgroundColor = [UIColor whiteColor];
}

// 注册Cell
- (void)registerCells
{
    UINib *nib = [UINib nibWithNibName:[BinningBracketCell reuseIdentifier] bundle:nil];
    [_myTableView registerNib:nib forCellReuseIdentifier:[BinningBracketCell reuseIdentifier]];
}

#pragma mark - initArray
// 初始化数组
- (NSMutableArray *)scanDataArray
{
    if (!_scanDataArray) {
        _scanDataArray = [[NSMutableArray alloc]init];
    }
    return _scanDataArray;
}

- (NSMutableArray *)GPSDataArray
{
    if (!_GPSDataArray) {
        _GPSDataArray = [[NSMutableArray alloc]init];
    }
    return _GPSDataArray;
}

#pragma mark - recoveryData
// 恢复数据
-(void)recoveryData
{
    if (_binningBracketModel != nil) {
        // 恢复集装箱编号
        _containerTF.text = _binningBracketModel.containerNo;
        // 支架或托盘编号
        NSArray *sequenceDataArray = [_binningBracketModel.stentsOrTrayNo componentsSeparatedByString:@","];
        _scanDataArray = [NSMutableArray arrayWithArray:sequenceDataArray];
        // GPS编号
        NSArray *gpsDataArray = [_binningBracketModel.gpsNo componentsSeparatedByString:@","];
        _GPSDataArray = [NSMutableArray arrayWithArray:gpsDataArray];
        [self.myTableView reloadData];
    }
}

// 修改/恢复支架数据
- (void)recoveryBracketData:(NSString *)contentStr index:(NSInteger)index type:(NSString *)type
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    BinningBracketCell *binningBracketCell = [self.myTableView cellForRowAtIndexPath:indexPath];
    if ([type isEqualToString:@"1"]) {
        binningBracketCell.contentLabel.text = contentStr;
    }else if ([type isEqualToString:@"2"]) {
        binningBracketCell.GPSLabel.text = contentStr;
    }
}

#pragma mark - changeAlertView
// 修改弹框视图
- (void)changeAlertView:(NSIndexPath *)indexPath type:(NSString *)type
{
    BinningBracketCell *binningBracketCell = [self.myTableView cellForRowAtIndexPath:indexPath];
    
    NSString *textFieldMessage = [type isEqualToString:@"1"] ? binningBracketCell.contentLabel.text : binningBracketCell.GPSLabel.text;
    
    if (![textFieldMessage isEqualToString:@"请扫码支架/托盘编码"]) {
        // 弹出修改弹框视图
        UIAlertView *editAlert = [[UIAlertView alloc] initWithTitle:@"" message:@"可根据需求进行修改" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        editAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
        // 修改的编码
        [[editAlert textFieldAtIndex:0] setText:textFieldMessage];
        
        // 防止循环引用
        WEAK_REF(self);
        
        editAlert.tapBlock = ^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == alertView.firstOtherButtonIndex) {
                NSString *contentStr = [[alertView textFieldAtIndex:0] text];
                // 修改/恢复支架数据
                [weak_self recoveryBracketData:contentStr index:indexPath.row type:type];
                // 修改数组数据
                if ([type isEqualToString:@"1"]) {
                    [weak_self.scanDataArray replaceObjectAtIndex:indexPath.row withObject:contentStr];
                }else if ([type isEqualToString:@"2"]) {
                    [weak_self.GPSDataArray replaceObjectAtIndex:indexPath.row withObject:contentStr];
                }
            } else if (buttonIndex == alertView.cancelButtonIndex) {
                NSLog(@"Cancelled.");
            }
        };
        //开始编辑才会显示确定
        //        av.shouldEnableFirstOtherButtonBlock = ^BOOL(UIAlertView *alertView){
        //            return ([[[alertView textFieldAtIndex:1] text] length] > 0);
        //        };
        
        [editAlert show];
    }
}

#pragma mark - pushVinCameraVC
// 跳转Vin条形码扫码页面
- (void)pushVinCameraVC:(NSIndexPath *)indexPath type:(NSString *)type
{
    ScanVC *scanVC = [[ScanVC alloc]init];
    scanVC.style = [StyleDIY notSquare];
    scanVC.isOpenInterestRect = YES;
    scanVC.libraryType = SLT_Native;
    scanVC.scanCodeType = SCT_BarCode128;
    scanVC.indexPath = indexPath;
    // 防止循环引用
    WEAK_REF(self);
    // 扫码结果返回更新 Block
    [scanVC setScanBlock:^(NSString *scanContentStr, NSIndexPath *indexPath){
        // 更新数据
        if ([type isEqualToString:@"1"]) {
            [weak_self.scanDataArray replaceObjectAtIndex:indexPath.row withObject:scanContentStr];
        }else if ([type isEqualToString:@"2"]) {
            [weak_self.GPSDataArray replaceObjectAtIndex:indexPath.row withObject:scanContentStr];
        }
        //同步更新支架/托盘编号
        BinningBracketCell *binningBracketCell = [weak_self.myTableView cellForRowAtIndexPath:indexPath];
        if ([type isEqualToString:@"1"]) {
            binningBracketCell.contentLabel.text = scanContentStr;
        }else if ([type isEqualToString:@"2"]) {
            binningBracketCell.GPSLabel.text = scanContentStr;
        }
    }];

    [self.navigationController pushViewController:scanVC animated:YES];
}

#pragma mark - Action
// 添加按钮
- (IBAction)addBtnAction:(UIButton *)sender
{
    // 添加支架/托盘
    [self.scanDataArray addObject:@""];
    // 添加GPS
    [self.GPSDataArray addObject:@""];
    [_myTableView reloadData];
}
// 保存按钮 Action
- (IBAction)saveBtnAction:(UIButton *)sender
{
    // ============保存到本地==========
    // 校验集装箱编号
    if (JudgeStrEqualNull(self.containerTF.text)) {
        [MBProgressHUD showError:ContainerPrompt];
        return;
    }
    
    BinningBracketModel *binningBracketModel = [[BinningBracketModel alloc]init];
    binningBracketModel.containerNo = self.containerTF.text;
    binningBracketModel.stentsOrTrayNo = [_scanDataArray componentsJoinedByString:@","];
    binningBracketModel.gpsNo = [_GPSDataArray componentsJoinedByString:@","];
    binningBracketModel.directionNo = self.trainShiftModel.departDirection;
    binningBracketModel.date = [self.trainShiftModel.date stringByReplacingOccurrencesOfString:@"-" withString:@""];
    binningBracketModel.location = self.trainShiftModel.location;
    binningBracketModel.supplier = self.trainShiftModel.supplier;
    // 用户ID 测试暂时写101
    binningBracketModel.userId = TestUserId;
    binningBracketModel.createTime = [[MAAFConfig sharedInstance] getNowTime];
    // 判断数据库中是否已有数据
    if (_binningBracketModel) {
        // 指定支架/托盘装车数据的ID
        if (_binningBracketModel.bracketId == 0) {
            // 如果westId = 0,则刚刚保存过,在存储列表的数据最顶端,否则westId不可能等于0
            // 查询保存的最后一条数据
            NSMutableArray *dataArray = [RailTransportDao selectBinningBracket:TestUserId];
            if (dataArray.count > 0) {
                BinningBracketModel *tmpModel = dataArray[0];
                binningBracketModel.bracketId = tmpModel.bracketId;
            }
        }else{
            // 1.保存列表跳转有westId直接赋值
            // 2.保存后更新数据
            binningBracketModel.bracketId = _binningBracketModel.bracketId;
        }
        // 更新支架/托盘装车表中数据
        BOOL state = [RailTransportDao updateBinningBracket:binningBracketModel];
        if (state) {
            // 更新Model,可以根据westId更新本地已保存数据
            _binningBracketModel = binningBracketModel;
            
            [MBProgressHUD showSuccess:@"更新成功"];
        }else{
            [MBProgressHUD showError:@"更新失败"];
        }
    }else{
        // 添加新支架/托盘装车表中
        BOOL state = [RailTransportDao addBinningBracket:binningBracketModel];
        if (state) {
            // 保存Model,可以根据westId更新本地已保存数据
            _binningBracketModel = binningBracketModel;
            
            [MBProgressHUD showSuccess:@"保存成功"];
        }else{
            [MBProgressHUD showError:@"保存失败"];
        }
    }
}
// 上传按钮 Action
- (IBAction)uploadBtnAction:(UIButton *)sender
{
    
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _scanDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 防止循环引用
    WEAK_REF(self);
    
    BinningBracketCell *cell = [tableView dequeueReusableCellWithIdentifier:[BinningBracketCell reuseIdentifier] forIndexPath:indexPath];
    cell.indexPath = indexPath;
    // 扫码托盘/支架更新数据 Block
    [cell setUpdateDataBlock:^(NSIndexPath *indexPath, NSString *type){
        // 键盘收起
        [weak_self.containerTF resignFirstResponder];
        // 跳转Vin条形码扫码页面
        [weak_self pushVinCameraVC:indexPath type:type];
    }];
    // 修改支架/托盘编码 Block
    [cell setChangeCodeBlock:^(NSIndexPath *indexPath, NSString *type){
        if (indexPath.section < 2) {
            // 键盘收起
            [weak_self.containerTF resignFirstResponder];
            // 修改弹框视图
            [weak_self changeAlertView:indexPath type:type];
        }
    }];
    // 设置数据
    [cell setData:_scanDataArray[indexPath.row] GPSStr:_GPSDataArray[indexPath.row]];
    return cell;
}
#pragma mark - TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 88;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 移除数据
        [_scanDataArray removeObjectAtIndex:indexPath.row];
        [_GPSDataArray removeObjectAtIndex:indexPath.row];
        // 移除单元格
//        [_myTableView reloadData];
        [_myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

// 设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
